package com.ecoolex.discount.sales.core.manager;

import com.ecoolex.discount.sales.core.dao.YouWorldUserDAO;
import com.ecoolex.discount.sales.entity.YouWorldUser;
import com.ecoolex.discount.sales.entity.YouWorldUser.Column;
import com.ecoolex.discount.sales.entity.YouWorldUserExample;
import com.ecoolex.discount.sales.entity.YouWorldUserExample.Criteria;
import com.ecoolex.discount.sales.pojo.AddYouWorldUserDTO;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.pojo.Sorting;
import com.ecoolex.framework.common.pojo.Sortings;
import com.ecoolex.framework.common.util.Check;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class YouWorldUserManager {
	
    @Autowired
    private YouWorldUserDAO dao;
    
    public YouWorldUser get(Integer id) {
		return dao.selectByPrimaryKeyWithLogicalDelete(id, YouWorldUser.NOT_DELETED);
	}
    
    public YouWorldUser getByPhone(String phone) {
    	YouWorldUserExample example = new YouWorldUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andPhoneEqualTo(phone).andDeletedEqualTo(YouWorldUser.NOT_DELETED);
		return dao.selectOneByExample(example);
    }

	public Pagination<YouWorldUser> query(String phone, Sorting[] sorts, Page page) {
		YouWorldUserExample example = new YouWorldUserExample();
		Criteria criteria = example.createCriteria();
		if(Check.notNull(phone)) {
			criteria.andPhoneEqualTo(phone);
		}
		criteria.andDeletedEqualTo(YouWorldUser.NOT_DELETED);
		example.setOffset(page.getFirstIndex());
		example.setRows(page.getPageSize());
		example.orderBy(Sortings.builder(sorts).toSql());
		return Pagination.create(page, 
			dao.countByExample(example),
			() -> dao.selectByExample(example));
	}

	public void batchAdd(List<AddYouWorldUserDTO> recordList, String createUser){
		for (AddYouWorldUserDTO record : recordList) {
			if(Check.notNull(getByPhone(record.getPhone()))) {
				continue;
			}
			record.setDeleted(YouWorldUser.NOT_DELETED);
			record.setCreateUser(createUser);
			record.setCreateTime(Date.from(Instant.now()));
			record.setUpdateUser(createUser);
			record.setUpdateTime(Date.from(Instant.now()));
			dao.insert(record);
		}
	}

	public void delete(YouWorldUser record, String updateUser){
		record.setDeleted(YouWorldUser.IS_DELETED);
		record.setUpdateTime(Date.from(Instant.now()));
		record.setUpdateUser(updateUser);
		dao.updateByPrimaryKeySelective(record, Column.deleted,Column.updateUser,Column.updateTime);
	}
}